<?php

/**
 * Created by PhpStorm
 * Author niuyongqiang@kungeek.com
 * Date 2022/3/2 11:11
 */

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class BaseModel extends Model
{
    protected $guarded = [];
    protected $queryModel = null;

    /**
     * 获取单条记录的基本信息
     */
    public function getInfo($condition, $field = '*'): array
    {
        $info = DB::table($this->table)->where($condition)->select($field)
            ->first();
        return $info ? get_object_vars($info) : [];
    }

    /**
     * 拼接sql条件
     * @return void
     * @throws Exception
     */
    public function spliceSQL()
    {
        //没有实例化model
        if (empty($this->queryModel))
            throw new Exception("not new model in spliceSQL");

        if (!empty($whereArr['where'])) {
            $this->queryModel->where($whereArr['where']);
        }
        if (!empty($whereArr['whereLike'])) {
            foreach ($whereArr['whereLike'] as $value) {
                $this->queryModel->where($value[0], $value[1], $value[2]);
            }
        }
        if (!empty($whereArr['whereUnequal'])) {
            foreach ($whereArr['whereUnequal'] as $value) {
                $this->queryModel->where($value[0], $value[1], $value[2]);
            }
        }
        if (!empty($whereArr['whereIn'])) {
            foreach ($whereArr['whereIn'] as $value) {
                $this->queryModel->whereIn($value[0], $value[1]);
            }
        }

    }

    /**
     * 查询一定条件下的列表
     * @param array $condition
     * @param array $field
     * @param string $order
     * @param string $group
     * @return Collection
     */
    public function getQuery(array $condition = [], array $field = ['*'], string $order = '', string $group = ''): Collection
    {
        $order = trim($order);
        if (empty($group)) {
            $list = Db::table($this->table)->where($condition)->orderByRaw($order)->select($field)->get();
        } else {
            $list = Db::table($this->table)->where($condition)->groupByRaw($group)->orderByRaw($order)->select($field)->get();
        }
        return $list;
    }

    public static function getNotInTitleId($whereNotId, $whereOrKey, $whereOrOne): array
    {
        $query = self::query();

        if (!empty($whereNotId)){
            $query->whereNotIn('id', $whereNotId);
        }

        $query->where(function ($queryTran) use ($whereOrOne, $whereOrKey) {
            if (!empty($whereOrOne)){
                $queryTran->orWhere($whereOrKey, '=', $whereOrOne);
            }

        });

        $user =  $query->get();
        return $user ? $user->toArray() : [];
    }
}
